//选择图片并回显到指定dom中(图片样式需要自己配置)
const zbSelectImg = function(){
    this.onSelected = null; //选则图片后执行回调
    this.onClickImg = null; //点击图片缩略图后的回调
    this.files = []; //存放自动生成的input对象, 可用于上传到后端

    //输入图片
    this.addImage = function (config) {
        //初始化input标签
        let input = document.createElement('input');
        for (let k in config['attr']) {
            input.setAttribute(k, config['attr'][k]);
        }
        input.setAttribute('type', 'file');
        input.setAttribute('data-params', this.encodeObj(config['params']));
        input.setAttribute('data-box-id', config['img_box_id']);
        input.addEventListener('input', this.changeImage.bind(this));

        this.files.push(input);

        if (config['attr']['id'] === undefined) {
            config['attr']['id'] = 'input_'+this.files.length;
            input.setAttribute('id', config['attr']['id']);
        }

        input.click(); //触发点击事件, 让用户选择图片
    }

    //改变输入的图片的事件
    this.changeImage = function (e) {
        let obj = e.target;
        console.log(obj);
        
        let objImage = obj.files[0];
        if (!objImage.size) {
            alert('未找到图片, 请重新选择');
            return false;
        }

        //回显图片到页面指定位置
        let image_box_id = obj.getAttribute('data-box-id');
        let imageBox = document.getElementById(image_box_id);
        let that = this;
        let reader = new FileReader();
        reader.onload = function(evt) {
            let img = document.createElement('img');
            img.setAttribute('id', 'img_'+that.files.length);
            if (typeof that.onClickImg === 'function') {
                img.addEventListener('click', that.onClickImg); //注册点击事件
            }
            img.src = evt.target.result;
            imageBox.appendChild(img);
        };

        reader.readAsDataURL(objImage);

        //选择图片后回调
        let params = this.decodeObj(obj.getAttribute('data-params'));
        params['img_name'] = objImage.name;
        params['input_id'] = obj.getAttribute('id');
        if (typeof this.onSelected === 'function') {
            this.onSelected(params);
        }
    }

    this.encodeObj = function (obj) {
        return encodeURIComponent(JSON.stringify(obj));
    }

    this.decodeObj = function (str) {
        return JSON.parse(decodeURIComponent(str));
    }
}
/**
 * 用法举例:
    let seleimg = new zbSelectImg();
        
    //选中图片后回调
    seleimg.onSelected = function(params) {
        console.log(params);
        console.log(seleimg.files);
    }

    //点击缩略图后回调
    seleimg.onClickImg = function(e) {
        console.log(e.target);
    }

    //chrome 需要用户主动发起选择图片的行为
    function select_img() {
        seleimg.addImage({attr:{}, img_box_id:'selected', params:{a:1,b:2}});
    }
 */